package com.juku2024.juku.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.R
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.callback.OnSearchKeySelectedListener
import com.juku2024.juku.model.CategorySearchTagModel
import com.juku2024.juku.tools.DisplayUtil


class CategorySearchKeyAdapter(
    private val category: ArrayList<CategorySearchTagModel>
) : RecyclerView.Adapter<CategorySearchKeyAdapter.CategoryKeyListViewHolder>() {

    var onSearchKeySelected: OnSearchKeySelectedListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryKeyListViewHolder {
        return CategoryKeyListViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.item_category_search_key1,
                parent,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return category.size
    }

    override fun onBindViewHolder(holder: CategoryKeyListViewHolder, position: Int) {
        holder.bind(category[position], onSearchKeySelected)
    }

    class CategoryKeyListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val rg: RadioGroup = itemView.findViewById(R.id.rg_category_key)

        fun bind(
            categoryBean: CategorySearchTagModel,
            onSearchKeySelected: OnSearchKeySelectedListener?
        ) {
            val data = categoryBean.data ?: return
            data.forEachIndexed { index, bean ->
                val rb: RadioButton = LayoutInflater.from(rg.context).inflate(
                    R.layout.item_category_key_text,
                    null
                ) as RadioButton

                rb.text = bean.name
                rb.id = index
                if (index == categoryBean.checkedPos) {
                    rb.isChecked = true
                }
                val param = RadioGroup.LayoutParams(
                    RadioGroup.LayoutParams.WRAP_CONTENT,
                    RadioGroup.LayoutParams.WRAP_CONTENT
                )
                param.rightMargin = DisplayUtil.dp2px(BaseApplication.context, 3f)
                if (index == 0) {
                    param.leftMargin = DisplayUtil.dp2px(BaseApplication.context, 16f)
                }
                rg.addView(rb, param)
            }

            rg.setOnCheckedChangeListener { _, checkedId ->
                if (data.size <= checkedId || checkedId == -1) return@setOnCheckedChangeListener
                val keyModel = data[checkedId]
                categoryBean.checkedPos = checkedId
                onSearchKeySelected?.onSearchKeySelected(
                    keyModel.id,
                    categoryBean.classes,
                    keyModel
                )
            }
        }
    }


}